package com.develop.BusinessGatewayService;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.develop.BeanUtils.Message;
import com.develop.BeanUtils.MsgType;
import com.develop.BeanUtils.SharedStorage;
import com.develop.vo.AlarmMsgVo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

/**
 * 客户端 handler
 **/

public class BusinessGatewayClientHandler extends SimpleChannelInboundHandler<AlarmMsgVo> {
	private static final Logger LOG = LoggerFactory.getLogger(BusinessGatewayClientHandler.class);
	private BusinessGatewayClient businessGatewayClient;
	private String cityCode;
	private String firmCode;
	private String omcType;

	public BusinessGatewayClientHandler(String host, int port, String cityCode, String firmCode, String omcType) {
		this.businessGatewayClient = new BusinessGatewayClient(host, port, cityCode, firmCode, omcType);
		this.cityCode = cityCode;
		this.firmCode = firmCode;
		this.omcType = omcType;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, AlarmMsgVo alarmMsgVo) throws Exception {
		try {
			if (alarmMsgVo.getMsgType() == MsgType.reqSyncAlarmMsg.getIndex()) {
				SharedStorage.getGatewayClient().writeAndFlush(alarmMsgVo);
			} else if (alarmMsgVo.getMsgType() == MsgType.reqSyncAlarmFile.getIndex()) {
				SharedStorage.getGatewayClient().writeAndFlush(alarmMsgVo);
			}
		} finally {
			ReferenceCountUtil.release(alarmMsgVo);
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		SharedStorage.setBusinessGatewayClientChannel(ctx.channel());
		LOG.info("业务网关通道已连接！");
		JSONObject msgBodyJSON = new JSONObject();
		msgBodyJSON.put("cityCode", cityCode);
		msgBodyJSON.put("firmCode", firmCode);
		msgBodyJSON.put("omcType", omcType);

		AlarmMsgVo alarmMsgVo = Message.generateMessage((byte) MsgType.reqLoginAlarm.getIndex(), msgBodyJSON.toString());
		ctx.channel().writeAndFlush(alarmMsgVo);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		LOG.info("与业务网关断开连接...");
		// 使用过程中断线重连
		final EventLoop eventLoop = ctx.channel().eventLoop();
		eventLoop.schedule(() -> businessGatewayClient.start(), 10, TimeUnit.SECONDS);
		ctx.fireChannelInactive();
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			if (event.state().equals(IdleState.WRITER_IDLE)) {
				/** 发送心跳,保持长连接 */
				StringBuffer msgBodyBuffer = new StringBuffer();
				msgBodyBuffer.append(MsgType.reqHeartBeat + ";");
				msgBodyBuffer.append("reqId=0");

				AlarmMsgVo alarmMsgVo = Message.generateMessage((byte) MsgType.reqHeartBeat.getIndex(), msgBodyBuffer.toString());
				ctx.channel().writeAndFlush(alarmMsgVo);
				LOG.info("向业务网关发送心跳...");
			}
		}
		super.userEventTriggered(ctx, evt);
	}
}
